package com.maple.common.utils

import android.serialport.SerialPort
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream


/**
 * Tip: 串口连接
 * 串口通信通常用于与嵌入式设备或传感器进行数据交互。Android 本身并不直接支持串口通信，
 * 但可以通过第三方库（如 android-serialport-api）实现
 * 需要权限
 *
 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 * <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
 *
 * 需要导入对应的SO
 * 镜像地址：https://github.com/licheedev/Android-SerialPort-API
 *
 * Create by SeVen on 2025/4/2 9:28
 */
class SerialPortHelper() {
    private var serialPort: SerialPort? = null
    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null

    /**
     * 打开串口
     * Open serial port
     *
     * @param devicePath
     * @param baudRate
     * @return
     */
    fun openSerialPort(devicePath: String, baudRate: Int): Boolean {
        try {
            serialPort = SerialPort(File(devicePath), baudRate)
            inputStream = serialPort?.inputStream
            outputStream = serialPort?.outputStream
            return true
        } catch (e: IOException) {
            e.printStackTrace()
            return false
        }
    }

    // 关闭串口
    fun closeSerialPort() {
        serialPort?.close()
        serialPort = null
    }

    // 发送数据
    fun sendData(data: ByteArray?) {
        try {
            outputStream?.write(data)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    // 读取数据
    fun readData(): ByteArray? {
        try {
            if (inputStream != null) {
                val buffer = ByteArray(1024)
                val size = inputStream!!.read(buffer)
                if (size > 0) {
                    val result = ByteArray(size)
                    System.arraycopy(buffer, 0, result, 0, size)
                    return result
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }
}